import { List_my } from '@/services/chdtuan';
import { copyToClipboard, groupOrders } from '@/utils/format';
import {
  ActionType,
  FooterToolbar,
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Typography } from 'antd';
import dayjs from 'dayjs';
import { useRef, useState } from 'react';
const { Paragraph } = Typography;

function OrderHistory() {
  const actionRef = useRef<ActionType>();
  const [selectedRowsState, setSelectedRows] = useState<any[]>([]);

  const getList = async (orderList, page = 1) => {
    let arr = orderList;
    const { data } = await List_my({
      Page: page,
    });

    arr = [...arr, ...data];

    if (data.length === 5) {
      const startDate = dayjs(data[4].date);
      const endDate = dayjs();
      const daysDifference = endDate.diff(startDate, 'day');
      console.log(daysDifference, 'daysDifference');
      if (daysDifference < 365) {
        arr = await getList(arr, page + 1);
      }
    }
    return arr;
  };

  const onCopy1 = () => {
    let copyText = '';
    selectedRowsState.forEach((item) => {
      let text = '';
      item.orderCode.forEach((code) => {
        text = text + '\n' + code;
      });
      copyText = copyText + '\n' + text;
    });
    copyToClipboard(copyText);
  };

  // 批量复制
  const onCopy = () => {
    let copyText = '';

    const list = groupOrders({
      orders: selectedRowsState,
      timeKey: 'date',
      orderNameKey: 'orderName',
      orderCodeKey: 'orderCode',
    });

    Object.keys(list).forEach((key) => {
      copyText = copyText + '\n\n--------------' + key + '--------------';
      Object.keys(list[key]).forEach((k) => {
        copyText = copyText + '\n\n' + `// ${k}` + '\n';
        list[key][k].forEach((code) => {
          copyText = copyText + code + '\n';
        });
      });
    });
    copyToClipboard(copyText);
  };

  const columns = [
    {
      title: '订单物品',
      dataIndex: 'orderName',
      key: 'orderName',
      hideInSearch: true,
    },
    {
      title: '领奖编码',
      key: 'orderCode',
      dataIndex: 'orderCode',
      hideInSearch: true,
      render(_) {
        const text = _.join('\n');
        return (
          <Paragraph copyable={{ text }} style={{ display: 'flex' }}>
            <div className="pre">{text}</div>
          </Paragraph>
        );
      },
    },
    {
      title: '导出数量',
      key: 'num',
      dataIndex: 'num',
      hideInTable: true,
    },
    {
      title: '实付款',
      key: 'price',
      dataIndex: 'price',
      hideInSearch: true,
    },
    {
      title: '购买时间',
      key: 'date',
      dataIndex: 'date',
      valueType: 'dateRange',
      fieldProps: {
        // presets: rangePresets,
      },
      colSize: 1.5,
      render(_, row) {
        return row.date;
      },
    },
    {
      title: '领取状态',
      key: 'status',
      dataIndex: 'status',
      hideInSearch: true,
    },
  ];

  return (
    <PageContainer
      header={{
        title: '',
      }}
    >
      <ProTable<API.UserInfo>
        // headerTitle="查询表格"
        actionRef={actionRef}
        pagination={false}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        request={async ({ date, num }) => {
          let arr = await getList([]);

          if (date?.[0] && date?.[1]) {
            const startDate = dayjs(date[0]).startOf('day');
            const endDate = dayjs(date[1]).endOf('day');

            arr = arr.filter((item) => {
              const itemDate = dayjs(item.date).add(1, 'hour');

              return itemDate.isAfter(startDate) && itemDate.isBefore(endDate);
            });
          }

          if (num) {
            arr = arr.slice(0, num);
          }

          return {
            data: arr || [],
            success: true,
          };
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              项&nbsp;&nbsp;
            </div>
          }
        >
          <Button type="primary" onClick={onCopy1}>
            批量复制
          </Button>
          {/* <Button type="primary" onClick={onCopy}>
            批量分组复制
          </Button> */}
        </FooterToolbar>
      )}
    </PageContainer>
  );
}

export default OrderHistory;
